<template>
  <div class="common-layout">
    <el-container>
      <el-header class="header">
        <div class="header-left">
          <a href="/">
            <img src="/src/static/images/logo.png" width="160px" alt="logo" class="logo">
          </a>
          <!-- <h1 class="site-title">书香雅苑</h1> -->
        </div>
        <div class="search-container">
          <el-input placeholder="搜索图书" v-model="searchQuery" class="search-bar" clearable>
            <template #append>
              <el-button type="primary" @click="searchBooks">
                <el-icon>
                  <Search />
                </el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
        <div class="cart-tab">
          <el-button type="primary" style="margin-left: 16px" @click="showDrawer">购物车</el-button>
          <el-button type="primary" style="margin-left: 16px" @click="showOrderDrawer(); fetchOrders()">订单</el-button>
          <el-button @click="loginDialogVisible = true" v-if="!token">登录</el-button>
          <el-button @click="logout" v-else>退出登录</el-button>
        </div>
      </el-header>
      <el-drawer v-model="drawer" title="购物车" :with-header="true" size="780" class="custom-drawer">
        <div v-if="cartItems.length > 0" class="drawer-content">
          <el-table :data="cartItems" border class="custom-table">
            <el-table-column label="图书图片" width="150">
              <template #default="{ row }">
                <img :src="row.image" alt="book" class="book-image-table" />
              </template>
            </el-table-column>
            <el-table-column prop="title" label="图书名称" width="150"></el-table-column>
            <el-table-column prop="price" label="单价" width="80"></el-table-column>
            <el-table-column prop="quantity" label="数量" width="180">
              <template #default="{ row }">
                <el-input-number v-model="row.quantity" :min="1" :max="99"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="总价" width="60">
              <template #default="{ row }">
                {{ row.price * row.quantity }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{ row }">
                <el-button type="danger" size="small" @click="removeItem(row)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="clear-cart">
            <el-button type="danger" @click="clearCart">清空</el-button>
          </div>
          <div class="cart-footer">
            <span style="color: black;">总金额: {{ totalAmount.toFixed(2) }} 元</span>
            <el-button type="success" @click="innerDrawer = true">结算</el-button>
            <el-drawer v-model="innerDrawer" title="确认结算" :append-to-body="true" :before-close="handleClose">
              <el-input v-model="Note" placeholder="请输入备注信息" type="textarea"></el-input>
              <el-button type="success" @click="checkout" style="margin-top: 20px">提交订单</el-button>
            </el-drawer>
          </div>
        </div>
        <div v-else>
          <p style="color: black;">购物车为空</p>
        </div>
      </el-drawer>
      <el-drawer v-model="orderDrawer" title="订单" :with-header="true" size="885px" class="custom-drawer">
        <div v-if="orders.length > 0" class="drawer-content">
          <el-table :data="orders" border class="custom-table">
            <el-table-column prop="order_id" label="订单号" width="150"></el-table-column>
            <el-table-column prop="order_time" label="订单时间" width="180"></el-table-column>
            <el-table-column prop="order_money" label="订单金额" width="100"></el-table-column>
            <el-table-column prop="order_status" label="订单状态" width="100"></el-table-column>
            <el-table-column prop="order_note" label="备注" width="100"></el-table-column>
            <el-table-column label="操作" width="175">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="viewOrderDetails(row)">查看详情</el-button>
                <el-button v-if="row.order_status === '待支付'" type="success" size="small"
                  @click="orderPay(row)">支付</el-button>
              </template>
            </el-table-column>
            <el-drawer v-model="orderDetailDrawer" title="订单详情" :with-header="true" size="760px" :append-to-body="true">
              <div v-if="orderDetails && orderDetails.length > 0">
                <el-table :data="orderDetails" border>
                  <el-table-column prop="image" label="图片">
                    <template #default="scope">
                      <img :src="scope.row.image" style="width: 80px; height: 80px;">
                    </template>
                  </el-table-column>
                  <el-table-column prop="title" label="书名" />
                  <el-table-column prop="book_num" label="数量" />
                  <el-table-column prop="price" label="单价" />
                </el-table>
              </div>
              <div v-else>
                <p style="color: black;">订单详情为空</p>
              </div>
            </el-drawer>
          </el-table>
        </div>
        <div v-else>
          <p style="color: black;">暂无订单</p>
        </div>
      </el-drawer>
      <el-main>
        <el-carousel :interval="4000" type="card" height="300px" class="carousel-container">
          <el-carousel-item v-for="item in carouselImages" :key="item.id">
            <a :href="item.link" target="_blank">
              <img :src="item.url" class="carousel-image" :alt="item.title">
            </a>
          </el-carousel-item>
        </el-carousel>
        <el-row :gutter="30" class="book-row">
          <el-col :span="4" v-for="book in paginatedBooks" :key="book.id">
            <el-card>
              <img :src="book.image" class="book-image" alt="book cover" />
              <div style="margin-top: 14px">
                <h3>《{{ book.title }}》</h3>
                <p>作者：{{ book.author }}</p>
                <p>出版社：{{ book.press }}</p>
                <p style="font-style: italic;">"{{ book.about }}"</p>
                <div class="price-cart">
                  <p class="price">价格：￥{{ book.price }}</p>
                  <el-button type="success" size="small" @click="addToCart(book)">加入购物车</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-dialog title="选择支付方式" v-model="isPayDialogVisible" width="30%">
          <span>请选择支付方式：</span>
          <el-radio-group v-model="selectedPaymentMethod">
            <el-radio value="微信">微信</el-radio>
            <el-radio value="支付宝">支付宝</el-radio>
            <el-radio value="银行卡">银行卡</el-radio>
          </el-radio-group>
          <template #footer>
            <el-button @click="pay">确认支付</el-button>
          </template>
        </el-dialog>
        <div class="pagination"> <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[12, 24, 48, 100]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="totalBooks" @size-change="handleSizeChange" @current-change="handleCurrentChange" /></div>
      </el-main>
    </el-container>
  </div>
  <el-dialog v-model="loginDialogVisible" title="用户登录" width="380px" :close-on-click-modal="false" destroy-on-close
    top="30vh" center>
    <login-form @login-success="handleLoginSuccess" @switch-to-register="switchToRegister" />
  </el-dialog>

  <el-dialog v-model="registerDialogVisible" title="用户注册" width="380px" :close-on-click-modal="false" destroy-on-close
    top="20vh" center>
    <register-form @register-success="handleRegisterSuccess" @switch-to-login="switchToLogin" />
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
import router from "../../../router";
import { useStore } from "vuex";
import { ElMessage, ElMessageBox } from "element-plus";
import { postCreateOrderRequest, postPayOrderRequest, postOrderDetailRequest, getOrderDetailRequest, getOrdersRequest } from "../../axios/index";
import LoginForm from './LoginForm.vue';
import RegisterForm from './RegisterForm.vue';

const store = useStore();
const drawer = ref(false);
const innerDrawer = ref(false);
const cartItems = ref([]);
const Note = ref("");
const orderItems = ref({
  orderMoney: computed(() => totalAmount.value.toFixed(2)),
  orderPay: "未支付",
  orderNote: computed(() => Note.value)
});
const isPayDialogVisible = ref(false);
const orderDrawer = ref(false);
const orderDetailDrawer = ref(false);
const orders = ref([]);
const orderDetails = ref([]);
const searchQuery = ref("");
const allBooks = ref([]);
const books = ref([]);
const currentPage = ref(1);
const pageSize = ref(12);
const totalBooks = computed(() => books.value.length);
const token = computed(() => store.state.Authorization);
const loginDialogVisible = ref(false);
const registerDialogVisible = ref(false);

onMounted(async () => {
  await fetchBooks();
  // console.log(token.value);

});

const totalAmount = computed(() =>
  cartItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
);

const paginatedBooks = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return books.value.slice(start, end);
});

function showDrawer() {
  const token = localStorage.getItem('Authorization');
  if (!token) {
    // ElMessage.warning('请先登录');
    loginDialogVisible.value = true;
    return;
  }
  drawer.value = true;
}

function showOrderDrawer() {
  const token = localStorage.getItem('Authorization');
  if (!token) {
    // ElMessage.warning('请先登录');
    loginDialogVisible.value = true;
    return;
  }
  orderDrawer.value = true;
}

function addToCart(book) {
  const token = localStorage.getItem('Authorization');
  if (!token) {
    // ElMessage.warning('请先登录');
    loginDialogVisible.value = true;
    return;
  }
  const existingItem = cartItems.value.find(item => item.id === book.id);
  if (existingItem) {
    existingItem.quantity++;
  } else {
    cartItems.value.push({ ...book, quantity: 1 });
  }
  ElMessage.success(`添加《${book.title}》到购物车`);
}

function clearCart() {
  cartItems.value = [];
  ElMessage.success('购物车已清空');
}

const removeItem = (item) => {
  cartItems.value = cartItems.value.filter((i) => i.id !== item.id);
};

const checkout = async () => {
  try {
    const result = await postCreateOrderRequest({ data: orderItems.value });
    orderId.value = result.data.orderId;
    await postOrderDetailRequest({
      data: {
        orderId: orderId.value,
        cartItems: cartItems.value
      }
    });
    cartItems.value = [];
    innerDrawer.value = false;
    drawer.value = false;
    isPayDialogVisible.value = true;
    ElMessage.success(result.data.message);
  } catch (error) {
    ElMessage.error(error.response.data.message);
  }
};

const orderPay = (order) => {
  orderId.value = order.order_id;
  isPayDialogVisible.value = true;
  orderDrawer.value = false;
}

const selectedPaymentMethod = ref('微信');
const orderId = ref("");
const pay = async () => {
  try {
    const result = await postPayOrderRequest({
      data: {
        orderId: orderId.value,
        orderPay: selectedPaymentMethod.value
      }
    });
    isPayDialogVisible.value = false;
    ElMessage.success(result.data.message);
  } catch (error) {
    ElMessage.error(error.response.data.message);
    console.log(error);
  }
};

async function fetchOrders() {
  try {
    // 检查是否有token,即是否已登录
    const token = localStorage.getItem('Authorization');
    if (!token) {
      // ElMessage.warning('请先登录');
      // router.push('/login');
      return;
    }
    const response = await getOrdersRequest();
    orders.value = response.data;
  } catch (error) {
    console.error("获取订单失败:", error);
  }
}

async function viewOrderDetails(order) {
  try {
    const response = await getOrderDetailRequest({ orderId: order.order_id });
    orderDetails.value = response.data;
    orderDetailDrawer.value = true;
  } catch (error) {
    console.error("Failed to fetch order details:", error);
  }
}

const handleClose = (done) => {
  ElMessageBox.confirm('您确定要取消提交订单吗？')
    .then(() => {
      done();
    })
    .catch(() => {
      // 什么也不做
    });
};

async function fetchBooks() {
  try {
    const response = await axios.get("http://localhost:3000/api/books/info");
    allBooks.value = response.data;
    books.value = allBooks.value;
  } catch (error) {
    console.error("Failed to fetch books:", error);
  }
}

function searchBooks() {
  currentPage.value = 1;
  if (searchQuery.value.trim() === "") {
    books.value = allBooks.value;
  } else {
    books.value = allBooks.value.filter(
      (book) =>
        book.title.includes(searchQuery.value) ||
        book.author.includes(searchQuery.value) ||
        book.press.includes(searchQuery.value)
    );
  }
}

// const gotoClick = (url) => {
//   router.push({ path: url });
// };

function handleSizeChange(val) {
  pageSize.value = val;
}

function handleCurrentChange(val) {
  currentPage.value = val;
}

function logout() {
  token.value = "";
  store.dispatch('logout');
  cartItems.value = [];
  ElMessage.success('退出登录成功');
}

const carouselImages = ref([
  {
    id: 1,
    url: '/src/static/images/book1.jpg',
    link: 'https://book.dangdang.com/20241112_yhib'
  },
  {
    id: 2,
    url: '/src/static/images/book2.jpg',
    link: 'https://book.dangdang.com/20200522_m3h2'
  },
  {
    id: 3,
    url: '/src/static/images/book3.jpg',
    link: 'https://book.dangdang.com/20241106_v0da'
  },
  {
    id: 4,
    url: '/src/static/images/book4.jpg',
    link: 'https://book.dangdang.com/20241129_kz5h'
  }
]);

const handleLoginSuccess = () => {
  loginDialogVisible.value = false;
};

const handleRegisterSuccess = () => {
  registerDialogVisible.value = false;
  loginDialogVisible.value = true;
};

const switchToRegister = () => {
  loginDialogVisible.value = false;
  registerDialogVisible.value = true;
};

const switchToLogin = () => {
  registerDialogVisible.value = false;
  loginDialogVisible.value = true;
};
</script>

<style lang="less" scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #3c4a5c;
  color: white;
  padding: 15px 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.site-title {
  margin: 0;
  font-size: 32px;
  font-family: "STKaiti", "华文楷体", serif;
  font-weight: bold;
  color: #fff;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
}

.search-container {
  flex: 1;
  display: flex;
  justify-content: center;
  max-width: 400px;
  margin-left: 75px;
}

.search-bar {
  width: 100%;
}

.cart-tab {
  display: flex;
  align-items: center;
}

.pagination {
  display: flex;
  justify-content: center;
}

.el-main {
  padding: 10px 200px;
  position: relative;
  padding-bottom: 20px;
}

.book-row {
  margin-top: 40px;
  margin-bottom: 20px;
}

.book-image {
  height: 180px;
  width: 100%;
  object-fit: cover;
  display: block;
  border-radius: 8px;
}

.clear-cart {
  margin-right: 10px;
  display: flex;
  justify-content: end;
}

.el-card {
  height: 385px;
  width: 220px;
  overflow: hidden;
  margin-bottom: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  transition: transform 0.3s;

  &:hover {
    transform: translateY(-5px);
  }
}

.el-card h3 {
  font-size: 16px;
  color: #333;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.el-card p {
  margin: 6px 0;
  color: #666;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.el-card p:nth-child(4) {
  /* 简介样式 */
  font-style: italic;
  color: #909399;
  white-space: normal;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-clamp: 2;
  height: 40px;
}

.price-cart {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.price {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
  margin: 0 !important;
}

.el-button {
  padding: 8px 15px;
  height: auto;
}

.book-image-table {
  width: 100px;
  height: auto;
  display: block;
  border-radius: 4px;
}

body {
  font-family: "Arial", sans-serif;
  background-color: #f0f2f5;
}

.custom-drawer {
  :deep(.el-drawer__header) {
    margin-bottom: 0;
    padding: 20px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;

    span {
      font-size: 18px;
      font-weight: bold;
      color: #303133;
    }
  }

  .drawer-content {
    padding: 20px;
  }

  .custom-table {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;

    :deep(.el-table__header) {
      background-color: #f5f7fa;
    }
  }
}

.cart-footer {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 8px;
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .total-amount {
    font-size: 18px;
    font-weight: bold;
    color: #f56c6c;
  }
}

.carousel-container {
  margin-bottom: 30px;
  margin-top: 20px;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.carousel-title {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  color: white;
  font-size: 20px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  background-color: rgba(0, 0, 0, 0.5);
  padding: 8px 16px;
  border-radius: 4px;
}
</style>
